package logic

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"hm-zero-mall/apps/user/rpc/pb"

	"hm-zero-mall/apps/api/api/internal/svc"
	"hm-zero-mall/apps/api/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// Login 用户登录
func (l *LoginLogic) Login(req *types.LoginRequest) (resp *types.TokenResponse, err error) {
	user, err := l.svcCtx.UserRPC.Login(l.ctx, &pb.UserLoginRequest{Phone: req.Phone, Password: req.Password})
	if err != nil {
		return nil, err
	}

	userID := fmt.Sprintf("%d", user.Id)
	Uuid := uuid.New().String()
	tokenKey := l.svcCtx.Config.Token.Prefix + Uuid
	refreshTokenKey := l.svcCtx.Config.Token.RefreshPrefix + userID
	err = l.svcCtx.Redis.SetexCtx(l.ctx, tokenKey, userID, l.svcCtx.Config.Token.Expire)
	if err != nil {
		return nil, err
	}
	err = l.svcCtx.Redis.SetexCtx(l.ctx, refreshTokenKey, userID, l.svcCtx.Config.Token.RefreshExpire)
	if err != nil {
		return nil, err
	}
	return &types.TokenResponse{
		Token:         tokenKey,
		Expire:        int64(l.svcCtx.Config.Token.Expire),
		RefreshToken:  refreshTokenKey,
		RefreshExpire: int64(l.svcCtx.Config.Token.RefreshExpire),
	}, nil
}
